package com.huika.dealontop.control.shops.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.myinfo.adapter.SelectBonusAdapter;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.views.TitleBarHelper;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author chenyuan
 * @description：使用优惠券
 * @date 2015年11月16日 上午11:25:04
 */
public class UseBonusActivity extends BaseAct {


    public static String CITYID = "cityId";
    public static String HASSELECTCOUPONNUM = "hasSelectCouponNum";
    private ListView select_bonus_lv;
    private SelectBonusAdapter adapter;
    private Button btn_confirm_bonus;
    private LinearLayout select_coupon_loy;
    private EditText input_bonus_code_et;
//    private int cityId;
    private TextView select_bonus_tv;
    private String hasSelectCouponNum;

    @Override
    protected void initData() {
        super.initData();
//        cityId = getIntent().getIntExtra(CITYID, 0);
        hasSelectCouponNum = getIntent().getStringExtra(HASSELECTCOUPONNUM);
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_use_bonus);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R.string.use_bonus_title).setRightPop();
        select_bonus_lv = (ListView) findViewById(R.id.select_bonus_lv);
        btn_confirm_bonus = (Button) findViewById(R.id.btn_confirm_bonus);
        input_bonus_code_et = (EditText) findViewById(R.id.input_bonus_code_et);
        select_bonus_tv = (TextView) findViewById(R.id.select_bonus_tv);

        select_coupon_loy = (LinearLayout) findViewById(R.id.select_coupon_loy);
        select_coupon_loy.setVisibility(new LoginUtils(this).isLogin() ? View.VISIBLE : View.GONE);
        btn_confirm_bonus.setOnClickListener(this);
        adapter = new SelectBonusAdapter(this,TextUtils.isEmpty(hasSelectCouponNum)?"":hasSelectCouponNum);
        select_bonus_lv.setAdapter(adapter);
//        adapter.setGroup(setData());
        getGainDiscountCoup();
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        if (v.getId() == R.id.btn_confirm_bonus) {


            if (adapter.datas.isEmpty() && TextUtils.isEmpty(getInputStr(input_bonus_code_et))) {
                showToastMsg(getString(R.string.use_bonus_select_bonus_code));
                return;
            }

            if (!TextUtils.isEmpty(getInputStr(input_bonus_code_et)) && !adapter.datas.isEmpty()) {
                showToastMsg(getString(R.string.use_bonus_des_tips));
                return;
            }
            getUseDiscountCoup();
        }
    }

    private ArrayList<HashMap<String, String>> setData() {
        ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < 5; i++) {
            HashMap<String, String> bean = new HashMap<String, String>();
            bean.put("num", 10 + i + "");
            bean.put("price", 10 + i + "");
            datas.add(bean);
        }
        return datas;
    }

    /**
     * 获得优惠券
     */
    private void getGainDiscountCoup() {

        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        getUserId(ajaxParams);
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("pageSize", new LoginUtils(aty).isLogin() ? GlobalApp.getInstance().getUserModel().getCouponQuantity() : PAGE_SIZE);

        FormResultRequest<ArrayList<HashMap<String, String>>> getResultRequest = new FormResultRequest<ArrayList<HashMap<String, String>>>(
                UrlConstants.GAINDISCOUNTCOUP, getGainDiscountCoupReq, this,
                new TypeToken<RequestResult<ArrayList<HashMap<String, String>>>>() {
                }.getType());
        getResultRequest.setRequestParams(ajaxParams);
        executeRequest(getResultRequest);

    }

    /**
     * 使用优惠券
     */
    private void getUseDiscountCoup() {

        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

        if (TextUtils.isEmpty(getInputStr(input_bonus_code_et))) {
            ajaxParams.putCommonTypeParam("type", "1");//类型（1 使用优惠券 2 使用优惠码）
            ajaxParams.putCommonTypeParam("vouchersId", adapter.selectId);//使用优惠券ID

        } else {
            ajaxParams.putCommonTypeParam("type", "2");//类型（1 使用优惠券 2 使用优惠码）
            ajaxParams.putCommonTypeParam("discountCode", getInputStr(input_bonus_code_et));//使用优惠码
        }

        getUserId(ajaxParams);
//        ajaxParams.putCommonTypeParam("cityId", cityId + "");

        FormResultRequest<HashMap<String, String>> getResultRequest = new FormResultRequest<HashMap<String, String>>(
                UrlConstants.USEDISCOUNTCOUP, getUseDiscountCoupReq, this,
                new TypeToken<RequestResult<HashMap<String, String>>>() {
                }.getType());
        getResultRequest.setRequestParams(ajaxParams);
        executeRequest(getResultRequest);

    }

    private void getUserId(JSONWrapAjaxParams ajaxParams) {
        long u_id = GlobalApp.getInstance().getUserId();
        ajaxParams.putCommonTypeParam("userId", u_id);

    }

    private Response.Listener<RequestResult<HashMap<String, String>>> getUseDiscountCoupReq = new Response.Listener<RequestResult<HashMap<String, String>>>() {

        @Override
        public void onResponse(RequestResult<HashMap<String, String>> result) {
            if (result.flag == 1) {

//                int	type:类型（1 使用优惠券 2 使用优惠码）
//                long	ID: （优惠券/优惠码ID）
//                string	activityType:优惠码类型（1代金券，2折扣）
//                string	discountAmount:优惠金额
//                string	discount:折扣率

                if (result.getRs() != null) {
                    Intent intent = new Intent(aty,
                            SubmitOrderActivity.class);
                    intent.putExtra(SubmitOrderActivity.PRICE_COUPON,
                            result.getRs());
                    intent.putExtra(SubmitOrderActivity.INPUT_COUPON_CODE,
                            getInputStr(input_bonus_code_et));
                    Log.d("cy", "result.getRs():" + result.getRs());
                    setResult(2000, intent);
                    finish();
                }


            }
//            showToastMsg(result.msg);
            dismissLoadingDialog();

        }
    };


    private Response.Listener<RequestResult<ArrayList<HashMap<String, String>>>> getGainDiscountCoupReq = new Response.Listener<RequestResult<ArrayList<HashMap<String, String>>>>() {

        @Override
        public void onResponse(RequestResult<ArrayList<HashMap<String, String>>> result) {
            if (result.flag == 1) {

//                “vouchersId”：”456231”,
//                “vouchersAmount”：”B100”,
//                “couponQuantity”：”1”

                if (result.getRs() != null && result.getRs().size() > 0) {

                    if (CURRENT_PAGE == 1)
                        adapter.setGroup(result.getRs().size() > 1 ? dealResult(result.getRs()) : result.getRs());
                    else adapter.addItems(dealResult(result.getRs()));
                } else {
                    select_bonus_tv.setVisibility(View.GONE);
                }


            }
//            showToastMsg(result.msg);
            dismissLoadingDialog();

        }
    };

    /**
     * 显示的时候处理的rs
     */
    private ArrayList<HashMap<String, String>> dealResult(ArrayList<HashMap<String, String>> rs) {

        ArrayList<HashMap<String, String>> dealRs = new ArrayList<HashMap<String, String>>();

        if (rs.size() > 1) {
            for (int i = 0; i < rs.size(); i++) {
                HashMap<String, String> bean = rs.get(i);
                int num = 1;
//                for (int j = i + 1; j < rs.size(); j++) {
//                    if (bean.get("vouchersAmount").equals(rs.get(j).get("vouchersAmount"))) {
//                        num = Integer.parseInt(bean.get("couponQuantity"));
//                        num = num + 1;
//                    }
//                    bean.put("vouchersId", bean.get("vouchersId"));
//                    bean.put("vouchersAmount", bean.get("vouchersAmount"));
//                    bean.put("couponQuantity", num + "");
//                    dealRs.add(bean);
//                }

                for (int j = rs.size()-1; j >0; j--) {
                    if (bean.get("vouchersAmount").equals(rs.get(j).get("vouchersAmount"))) {
                        num = Integer.parseInt(bean.get("couponQuantity"));
                        num = num + 1;
                        rs.remove(j);
                    }
                    bean.put("vouchersId", bean.get("vouchersId"));
                    bean.put("vouchersAmount", bean.get("vouchersAmount"));
                    bean.put("couponQuantity", num + "");

                }
                dealRs.add(bean);
            }

        }

        Log.d("cy", "dealRs:" + dealRs);
        return dealRs;
    }


//    private void changeRefreshMode(int totalSize) {
//        if (totalSize == 0) {
//            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
//        } else if (adapter.getCount() >= totalSize) {
//            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
//        } else {
//            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.BOTH);
//        }
//    }

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        super.onErrorResponse(error);
        // enshipLv.onRefreshComplete();
        dismissLoadingDialog();
    }

}
